#include "xdemux_task.h"
#include <chrono>
extern "C" {
#include <libavformat/avformat.h>
}
using namespace std;

bool XDemuxTask::Open(const std::string &url, int timeout_ms) {
  LOGDEBUG("XDemuxTask::Open begin");
  demux_.set_c(nullptr); // 清楚原来的
  this->url_ = url;
  this->timeout_ms_ = timeout_ms;
  AVFormatContext *c = demux_.Open(url.c_str());
  if (!c)
    return false;
  demux_.set_c(c);
  demux_.set_time_out_ms(timeout_ms);
  LOGDEBUG("XDemuxTask::Open end");
  return true;
}

void XDemuxTask::Stop()
{
    XThread::Stop();
    // 清理
    demux_.set_c(nullptr);
}

bool XDemuxTask::Seek(long long pos_ms) {
    auto vp = demux_.CopyVideoPara();
    if (!vp)return false;
    auto pts = av_rescale_q(pos_ms,{1,1000},*vp->time_base);
	return demux_.Seek(pts, demux_.video_index());
}

void XDemuxTask::Main() {
  AVPacket pkt;
  while (!is_exit()) {
      if (is_pause()) {
          MSleep(1);
          continue;
      }
    if (!demux_.Read(&pkt)) {
      // 读取失败
      cout << "-" << flush;
      if (!demux_.is_connected() || demux_.IsTimeout()) {
        XDemuxTask::Open(url_, timeout_ms_);
      }
      std::this_thread::sleep_for(10ms);
      continue;
    }
    cout << "." << flush;
    // 传递给下一个线程
    //播放速度控制
    if (syn_type_ == XSYN_VIDEO &&
        pkt.stream_index == demux_.video_index())
    {
        auto dur = demux_.RescaleToMs(pkt.duration, pkt.stream_index);
        if (dur <= 0)
            dur = 40;
        //pkt.duration
        MSleep(dur);
    }
    Next(&pkt);
    av_packet_unref(&pkt);
    std::this_thread::sleep_for(10ms);
  }
  demux_.set_c(nullptr);
}

//void XDemuxTask::Do(AVPacket* pkt) {
//    if (!pkt)return;
//    //this->pkts_->push(pkt);
//}